<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="课堂主题" prop="classTopic">
        <el-input v-model="queryParams.classTopic" placeholder="请输入课堂主题" clearable size="small" style="width: 240px" />
      </el-form-item>

      <el-form-item label="教师" prop="teacherId">
        <el-select v-model="queryParams.teacherId" placeholder="请选择教师" clearable size="small" style="width: 240px">
          <el-option v-for="t in teacherOptions" :key="t.id" :label="t.name" :value="t.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="上课时间">
        <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" />
      </el-form-item>

      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 查询结果表格 -->
    <el-table v-loading="loading" :data="classList">
      <el-table-column label="课堂主题" align="center" prop="classTopic" />
      <el-table-column label="教师" align="center">
        <template slot-scope="scope">
          <span>{{ getTeacherName(scope.row.teacherId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="classTimeBegin">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.classTimeBegin) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="classTimeEnd">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.classTimeEnd) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课堂批次" align="center" prop="classBatch">
        <template slot-scope="scope">
          <span>{{ scope.row.classBatch }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="360">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="success" icon="el-icon-document" size="mini" @click="handleEvaluate(scope.row)">课堂评价</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新增/编辑/评价课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body :close-on-click-modal="false" style="margin-top: 0">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="课堂主题" prop="classTopic">
          <el-input v-model="form.classTopic" placeholder="请输入课堂主题" :disabled="title==='课堂评价'" />
        </el-form-item>

        <el-form-item label="上课时间">
          <el-date-picker v-model="classTimeRange" type="datetimerange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" :disabled="title==='课堂评价'" />
        </el-form-item>

        <!-- 教师选择 -->
        <el-form-item label="教师" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择教师" :disabled="title==='课堂评价'">
            <el-option v-for="t in teacherOptions" :key="t.userId" :label="t.nickName" :value="t.userId" />
          </el-select>
        </el-form-item>

        <!-- 关联绘本选择 -->
        <el-form-item label="关联绘本">
          <!-- 按钮部分 -->
          <div v-if="title!=='课堂评价'">
            <el-button v-if="title==='新增课程'" type="primary" size="mini" @click="bookDialogVisible = true">选择绘本</el-button>
            <el-button v-if="title==='修改课程'" type="warning" size="mini" @click="bookDialogVisible = true">重新选择绘本</el-button>
          </div>
          <!-- 标签部分，强制刷新用 key -->
          <div v-if="form.bookList && form.bookList.length" style="margin-top:10px;">
            <el-tag
              v-for="book in form.bookList"
              :key="book.id + '-' + title"
              :closable="title!=='课堂评价'"
              @close="removeBook(book)"
              style="margin-right:10px;"
            >
              {{ book.bookName }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 修改时拓展词汇 -->
        <template v-if="title === '修改课程'">
          <el-form-item label="拓展词汇">
            <draggable v-model="form.vocabularyList" handle=".drag-handle" animation="200">
              <transition-group tag="div" class="words-grid">
                <div v-for="(word, index) in form.vocabularyList" :key="index" class="word-card">
                  <span class="word-index">{{ index + 1 }}.</span>
                  <span class="drag-handle">☰</span><el-button type="danger" icon="el-icon-delete" size="mini" style="margin:10px;" @click="removeWord(index)">删除</el-button>
                  <div class="word-section">

                    <el-input v-model="word.vocabText" placeholder="单词" style="margin-bottom: 10px;" />
                    <el-upload
                      action=""
                      :http-request="(param) => uploadExtraImage(param, index)"
                      :limit="1"
                      :on-exceed="() => $message.warning('每个单词只能上传一张图片')"
                      accept="image/*"
                      :file-list="word.imageFileList"
                      list-type="picture-card"
                      style="margin-bottom: 10px;"
                    >
                      <i class="el-icon-plus"></i>
                    </el-upload>
                    <div class="audio-section">
                      <div class="button-row">
                      <el-button
                        type="primary"
                        icon="el-icon-microphone"
                        size="mini"
                        @click="startRecord(index)"
                        :disabled="recordingIndex === index"
                        style="margin-right: 0px;"
                      >{{ recordingIndex === index ? '录音中...' : '录音' }}</el-button>
                      <el-button
                        type="danger"
                        size="mini"
                        @click="stopRecord"
                        :disabled="recordingIndex !== index"
                      >停止</el-button>
                      </div>
                      <div  v-if="word.vocabAudio" style="margin-top: 5px;">
                        <audio :src="imagePrefix + word.vocabAudio" controls></audio>
                      </div>
                    </div>

                  </div>
                </div>
              </transition-group>
            </draggable>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="addWord">新增词汇</el-button>
          </el-form-item>
        </template>

        <!-- 课堂评价内容，仅在课堂评价时显示 -->
        <template v-if="title === '课堂评价'">
          <el-form-item label="拓展词汇">
            <div class="words-grid">
              <div v-for="(word, index) in form.vocabularyList" :key="index" class="word-card">
                <div class="word-section">
                  <el-input v-model="word.vocabText" placeholder="单词" disabled style="margin-bottom: 10px;" />
                  <el-upload
                    action=""
                    :file-list="word.imageFileList"
                    :limit="1"
                    :on-exceed="() => $message.warning('每个单词只能上传一张图片')"
                    list-type="picture-card"
                    disabled
                    style="margin-bottom: 10px;"
                  />
                  <div v-if="word.vocabAudio">
                    <audio :src="imagePrefix + word.vocabAudio" controls></audio>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>

          <!-- 学生选择 -->
          <el-form-item label="学生">
            <el-select v-model="form.studentId" placeholder="请选择学生" @change="handleStudentChange">
              <el-option v-for="s in studentOptions" :key="s.studentId" :label="s.studentEnglishName+'（'+s.studentName+'）'" :value="s.studentId" />
            </el-select>
          </el-form-item>

          <!-- 星级评价 -->
          <el-form-item label="课堂评分">
            <el-rate v-model="form.gradeDetermination" allow-half />
          </el-form-item>
          <!-- 积分输入框 -->
          <el-form-item label="课堂额外积分">
            <el-input-number v-model="form.classPoints" :min="0" :step="1" placeholder="请输入额外积分" />
          </el-form-item>
          <!-- 评论内容 -->
          <el-form-item label="课堂评论">
            <el-input type="textarea" v-model="form.teacherEvaluation" placeholder="请输入评价内容" />
          </el-form-item>

          <!-- 视频上传，仅在课堂评价时显示 -->
          <el-form-item label="上传视频" v-if="title==='课堂评价'">
            <div v-if="form.videoUpload" style="margin-top: 10px; ">
              <video :src="imagePrefix + form.videoUpload" controls style="max-width: 400px; height: 220px; border: 1px solid #ccc; border-radius: 6px; display:block; margin:0 ;" />
              <el-button type="danger" size="mini" style="margin-top:8px;" @click="removeVideo">删除视频</el-button>
            </div>
            <el-upload
              action=""
              class="upload-demo"
              drag
              :http-request="uploadVideo"
              accept="video/*"
              :limit="1"
              :on-exceed="() => $message.warning('只能上传一个视频')"
              :file-list="form.videoFileList"
              list-type="text"
              :on-remove="handleVideoRemove"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将视频拖到此处，或<em>点击上传</em></div>
            </el-upload>

          </el-form-item>
        </template>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绘本管理页面作为子组件弹窗 -->
    <el-dialog title="选择绘本" :visible.sync="bookDialogVisible" width="1200px" append-to-body>
      <textbook-manage @confirm="handleBookConfirm" @cancel="bookDialogVisible=false" :select-mode="true" />
    </el-dialog>
  </div>
</template>



<script>
import { listByTime, save, deleteById,getPictureBookByIds, update,getVocabularyByIds,studentListAll,evaluationSave,studentElevationGetById,selectTeacherList,checkInRecordByClassId } from "@/api/class/classSchedule";
import { uploadFilesByType } from "@/api/class/classSchedule";
import draggable from "vuedraggable";
import TextbookManage from "@/views/class/textbookManage/storybookM.vue";

export default {
  name: "classSchedule",
  components: { draggable, TextbookManage },
  data() {
    return {
      loading: false,
      classList: [],
      total: 0,
      showSearch: true,
      dateRange: [],
      open: false,
      title: "",
      studentOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classTopic: undefined,
        teacherId: undefined,
      },
      form: {
        id: undefined,
        classId: undefined,
        classTopic: undefined,
        classTimeBegin: undefined,
        classTimeEnd: undefined,
        bookList: [],
        pictureBookId: undefined,
        teacherId: undefined,
        vocabularyList: [],
        gradeDetermination: 0,
        teacherEvaluation: undefined,
        videoFileList: [],
        videoUpload: undefined,
        classPoints: 0,
      },
      classTimeRange: [],
      rules: {
        classTopic: [{ required: true, message: "课堂主题不能为空", trigger: "blur" }],
      },
      bookDialogVisible: false,
      bookSelectMode: true,
      teacherOptions: [
        { id: 't1', name: '张老师' },
        { id: 't2', name: '李老师' },
        { id: 't3', name: '王老师' }
      ],
      recordingIndex: null,
      mediaRecorder: null,
      audioChunks: [],
      imagePrefix: `${window.location.origin}/`
    };
  },
  created() {
    this.getList();

  },
  methods: {
    selectTeacherList(){
      selectTeacherList().then((response) => {
        this.teacherOptions = response.data;
      });
    },
    handleStudentChange(value) {
      studentElevationGetById({ studentId: value, classId: this.form.id }).then((response) => {
        const data = response.data || {};
        // 有值就填值，没值还原默认值
        this.$set(this.form, "videoUpload", data.videoUpload || undefined);
        this.$set(this.form, "classPoints", data.classPoints != null ? Number(data.classPoints) : 0);
        this.$set(this.form, "gradeDetermination", data.gradeDetermination != null ? Number(data.gradeDetermination) : 0);
        this.$set(this.form, "teacherEvaluation", data.teacherEvaluation || "");
      });
    },
    handleVideoRemove() {
      this.$set(this.form, "videoUpload",undefined); // 强制让 Vue 建立依赖
      this.form.videoFileList = [];
    },
    removeVideo() {
      this.$set(this.form, "videoUpload",undefined); // 强制让 Vue 建立依赖
      this.form.videoFileList = [];
    },
    getStudentListAll(){
      studentListAll().then((response) => {
        this.studentOptions = response.rows;

      });
    },
    /** 查询课程 */
    getList() {
      this.loading = true;
      listByTime(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.classList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增课程";
      this.selectTeacherList();
    },
    handleEdit(row) {
      this.form = { ...row, vocabularyList: [] };
      this.classTimeRange = [row.classTimeBegin, row.classTimeEnd];
      this.open = true;
      this.title = "修改课程";
      // 查询绘本名称vocabularyId
      if (row.pictureBookId) {
        getPictureBookByIds(row.pictureBookId).then(res => {
          if (res && res.data) {
            this.$set(this.form, "bookList", res.data); // 强制让 Vue 建立依赖
          }
        });
      }
      if (row.vocabularyId) {
        getVocabularyByIds(row.vocabularyId).then(res => {
          if (res && res.data) {
            const vocabList = res.data.map(item => {
              return {
                ...item,
                imageFileList: item.vocabImage
                  ? [{ name: item.vocabImage, url: this.imagePrefix + item.vocabImage }]
                  : []
              };
            });
            this.$set(this.form, "vocabularyList", vocabList);
          }
        });
      }
      this.selectTeacherList();

    },
    handleEvaluate(row) {
      this.form = { ...row, vocabularyList: [] };
      this.classTimeRange = [row.classTimeBegin, row.classTimeEnd];
      this.open = true;
      this.title = "课堂评价";
      // 查询绘本名称
      if ( row.pictureBookId) {
        getPictureBookByIds(row.pictureBookId).then(res => {
          if (res && res.data) {
            this.$set(this.form, "bookList", res.data); // 强制让 Vue 建立依赖
          }
        });
      }
      if (row.vocabularyId) {
        getVocabularyByIds(row.vocabularyId).then(res => {
          if (res && res.data) {
            const vocabList = res.data.map(item => {
              return {
                ...item,
                imageFileList: item.vocabImage
                  ? [{ name: item.vocabImage, url: this.imagePrefix + item.vocabImage }]
                  : []
              };
            });
            this.$set(this.form, "vocabularyList", vocabList);
          }
        });
      }
      //查询签到学生
      checkInRecordByClassId({'classId':this.form.id}).then(res => {
        if (res && res.data) {
          //this.$set(this.form, "bookList", res.data); // 强制让 Vue 建立依赖
          this.studentOptions = res.data
        }
      });
      this.selectTeacherList();
      /*this.getStudentListAll();*/
    },
    reset() {
      this.form = {
        id: undefined,
        classTopic: undefined,
        classTimeBegin: undefined,
        classTimeEnd: undefined,
        bookList: [],
        pictureBookId: undefined,
        teacherId: undefined,
        vocabularyList: []
      };
      this.classTimeRange = [];
      this.resetForm("form");
    },
    removeBook(book) {
      this.form.bookList = this.form.bookList.filter(b => b.id !== book.id);
    },
    handleBookConfirm(selectedBooks) {
      this.form.bookList = selectedBooks;
      this.bookDialogVisible = false;
    },
    addWord() {
      this.form.vocabularyList.push({ vocabText: '', vocabImage: '', vocabAudio: '', imageFileList: [] });
    },
    removeWord(index) {
      this.form.vocabularyList.splice(index, 1);
    },
    uploadExtraImage(param, index) {
      const formData = new FormData();
      formData.append("file", param.file);
      formData.append("fileType", "expand_vocabulary");
      uploadFilesByType(formData, "expand_vocabulary").then((res) => {
        if (res && res.url) {
          this.$set(this.form.vocabularyList[index], 'vocabImage', res.fileName);
          this.form.vocabularyList[index].imageFileList = [{ name: res.fileName, url: this.imagePrefix + res.fileName }];
        }
        param.onSuccess(res);
      }).catch(() => param.onError());
    },
    startRecord(index) {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
          this.mediaRecorder = new MediaRecorder(stream);
          this.audioChunks = [];
          this.recordingIndex = index;
          this.mediaRecorder.ondataavailable = e => this.audioChunks.push(e.data);
          this.mediaRecorder.onstop = () => {
            const blob = new Blob(this.audioChunks, { type: 'audio/mp3' });
            const formData = new FormData();
            formData.append("file", blob, `audio_${Date.now()}.mp3`);
            formData.append("fileType", "expand_vocabulary_audio");
            uploadFilesByType(formData, "expand_vocabulary_audio").then((res) => {
              if (res && res.url) {
                this.$set(this.form.vocabularyList[index], 'vocabAudio', res.fileName);
              }
            });
            this.recordingIndex = null;
          };
          this.mediaRecorder.start();
        });
      } else {
        this.$message.error("浏览器不支持录音功能");
      }
    },
    stopRecord() {
      if (this.mediaRecorder) {
        this.mediaRecorder.stop();
      }
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.classTimeBegin = this.classTimeRange[0];
          this.form.classTimeEnd = this.classTimeRange[1];
          this.form.classId = this.form.id;
          // 将选中的绘本ID拼接成字符串赋值给 pictureBookId
          this.form.pictureBookId = this.form.bookList.map(b => b.id).join(',');

          // 判断是新增还是修改
          let request;
          this.savingInstance = this.$loading({ lock: true, text: "正在保存，请稍候...", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)" });
          if (this.title === '课堂评价') {
            request = evaluationSave(this.form);
          }else if(this.form.id) {
            // 有 id，说明是修改
            request = update(this.form);
          } else {
            // 没有 id，说明是新增
            request = save(this.form);
          }

          request.then(() => {
            this.msgSuccess("保存成功");
            this.open = false;
            this.getList();
          }).catch((error) => {
            this.$message.error("保存失败: " + (error.message || '未知错误'));
          }).finally(() => {
            if (this.savingInstance) {
              this.savingInstance.close();
            }
          });
        }
      });
    },

    cancel() {
      this.open = false;
      this.reset();
    },
    handleDelete(id) {
      this.$confirm('确认删除该课程吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(id).then(() => {
          this.msgSuccess("删除成功");
          this.getList();
        });
      }).catch(() => {});
    },
    getTeacherName(id) {
      const teacher = this.teacherOptions.find(t => t.id === id);
      return teacher ? teacher.name : id;
    },
    uploadVideo(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      formData.append("fileType", "classroom_video");
      uploadFilesByType(formData, "classroom_video").then((res) => {
        if (res && res.url) {
          this.$set(this.form, "videoUpload", res.fileName); // 强制让 Vue 建立依赖
          this.form.videoFileList = [{ name: res.fileName, url: this.imagePrefix + res.fileName }];
        }
        param.onSuccess(res);
      }).catch(() => param.onError());
    },
  },
};
</script>

<style scoped>
.words-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.word-card {
  flex: 1 1 350px; /* 每个卡片大约 200px 宽 */
  max-width: 350px;
  border: 1px solid #eee;
  padding: 8px;
  border-radius: 4px;
  box-sizing: border-box;
}

.word-section {
  display: flex;
  flex-direction: column;
}

.drag-handle {
  cursor: move;
  margin-bottom: 10px;
}


.audio-section {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.button-row {
  display: flex;
  gap: 10px;
}

.word-index {
  font-weight: bold;
  margin-right: 8px;
  color: #666;
}

.el-dialog:not(.is-fullscreen) {
   margin-top: 0vh !important;
}
</style>

